const api = require('../../utils/api.js');

Page({
  data: {
    phone: '',
    smsCode: '',
    email: '',
    emailCode: '',
    password: '',
    confirmPassword: '',
    nickname: '',
    showPassword: false,
    showConfirmPassword: false,
    loading: false,
    agreed: false,
    canRegister: false,
    
    // 验证码相关
    phoneCodeSent: false,
    emailCodeSent: false,
    phoneCountdown: 60,
    emailCountdown: 60,
    
    // 密码强度
    passwordStrength: 0,
    strengthLabel: '',
    
    // 邮箱验证
    isValidEmail: false
  },

  onLoad(options) {
    // 页面加载时的初始化
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 手机号输入
  onPhoneInput(e) {
    const phone = e.detail.value;
    this.setData({ phone });
    this.checkCanRegister();
  },

  // 手机验证码输入
  onSmsCodeInput(e) {
    const smsCode = e.detail.value;
    this.setData({ smsCode });
    this.checkCanRegister();
  },

  // 邮箱输入
  onEmailInput(e) {
    const email = e.detail.value;
    const isValidEmail = this.validateEmail(email);
    this.setData({ 
      email,
      isValidEmail
    });
    this.checkCanRegister();
  },

  // 邮箱验证码输入
  onEmailCodeInput(e) {
    const emailCode = e.detail.value;
    this.setData({ emailCode });
    this.checkCanRegister();
  },

  // 密码输入
  onPasswordInput(e) {
    const password = e.detail.value;
    const { strength, label } = this.calculatePasswordStrength(password);
    this.setData({ 
      password,
      passwordStrength: strength,
      strengthLabel: label
    });
    this.checkCanRegister();
  },

  // 确认密码输入
  onConfirmPasswordInput(e) {
    const confirmPassword = e.detail.value;
    this.setData({ confirmPassword });
    this.checkCanRegister();
  },

  // 昵称输入
  onNicknameInput(e) {
    const nickname = e.detail.value;
    this.setData({ nickname });
  },

  // 切换密码显示
  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  // 切换确认密码显示
  toggleConfirmPasswordVisibility() {
    this.setData({
      showConfirmPassword: !this.data.showConfirmPassword
    });
  },

  // 发送手机验证码
  async sendPhoneCode() {
    if (!this.validatePhone(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await this.sendSmsCode(this.data.phone);
      
      if (res.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        
        this.setData({ phoneCodeSent: true });
        this.startPhoneCountdown();
      } else {
        wx.showToast({
          title: res.msg || '发送失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('发送手机验证码失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 发送邮箱验证码
  async sendEmailCode() {
    if (!this.data.isValidEmail) {
      wx.showToast({
        title: '请输入正确的邮箱地址',
        icon: 'none'
      });
      return;
    }

    try {
      const res = await this.sendEmailCodeAPI(this.data.email);
      
      if (res.code === 200) {
        wx.showToast({
          title: '验证码已发送',
          icon: 'success'
        });
        
        this.setData({ emailCodeSent: true });
        this.startEmailCountdown();
      } else {
        wx.showToast({
          title: res.msg || '发送失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('发送邮箱验证码失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 开始手机验证码倒计时
  startPhoneCountdown() {
    const timer = setInterval(() => {
      if (this.data.phoneCountdown > 0) {
        this.setData({
          phoneCountdown: this.data.phoneCountdown - 1
        });
      } else {
        clearInterval(timer);
        this.setData({
          phoneCodeSent: false,
          phoneCountdown: 60
        });
      }
    }, 1000);
  },

  // 开始邮箱验证码倒计时
  startEmailCountdown() {
    const timer = setInterval(() => {
      if (this.data.emailCountdown > 0) {
        this.setData({
          emailCountdown: this.data.emailCountdown - 1
        });
      } else {
        clearInterval(timer);
        this.setData({
          emailCodeSent: false,
          emailCountdown: 60
        });
      }
    }, 1000);
  },

  // 发送手机验证码API
  sendSmsCode(phone) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://192.168.10.101:5000/api/register/send_sms',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: { phone },
        success: (res) => resolve(res.data),
        fail: reject
      });
    });
  },

  // 发送邮箱验证码API
  sendEmailCodeAPI(email) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'http://192.168.10.101:5000/api/register/send_email',
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        data: { email },
        success: (res) => resolve(res.data),
        fail: reject
      });
    });
  },

  // 处理注册
  async handleRegister() {
    if (!this.data.agreed) {
      wx.showToast({
        title: '请先同意用户协议和隐私政策',
        icon: 'none'
      });
      return;
    }

    if (!this.validateForm()) {
      return;
    }

    this.setData({ loading: true });

    try {
      const res = await api.register(
        this.data.phone,
        this.data.password,
        this.data.nickname
      );

      if (res.code === 200) {
        wx.showToast({
          title: '注册成功',
          icon: 'success'
        });

        // 保存token
        wx.setStorageSync('access_token', res.data.access_token);
        wx.setStorageSync('refresh_token', res.data.refresh_token);

        // 延迟跳转
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }, 1500);
      } else {
        wx.showToast({
          title: res.msg || '注册失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('注册失败:', error);
      wx.showToast({
        title: error.message || '网络错误，请重试',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 验证表单
  validateForm() {
    if (!this.validatePhone(this.data.phone)) {
      wx.showToast({
        title: '请输入正确的手机号',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.smsCode || this.data.smsCode.length !== 6) {
      wx.showToast({
        title: '请输入6位手机验证码',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.isValidEmail) {
      wx.showToast({
        title: '请输入正确的邮箱地址',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.emailCode || this.data.emailCode.length !== 6) {
      wx.showToast({
        title: '请输入6位邮箱验证码',
        icon: 'none'
      });
      return false;
    }

    if (!this.validatePassword(this.data.password)) {
      wx.showToast({
        title: '密码需至少8位且包含字母和数字',
        icon: 'none'
      });
      return false;
    }

    if (this.data.password !== this.data.confirmPassword) {
      wx.showToast({
        title: '两次输入密码不一致',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 验证手机号
  validatePhone(phone) {
    return /^1[3-9]\d{9}$/.test(phone);
  },

  // 验证邮箱
  validateEmail(email) {
    return /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/.test(email);
  },

  // 验证密码
  validatePassword(password) {
    return /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password);
  },

  // 计算密码强度
  calculatePasswordStrength(password) {
    if (!password) {
      return { strength: 0, label: '' };
    }

    let strength = 0;
    let label = '';

    // 长度检查
    if (password.length >= 8) strength++;
    
    // 包含字母和数字
    if (/[A-Za-z]/.test(password) && /\d/.test(password)) strength++;
    
    // 包含特殊字符
    if (/[!@#$%^&*(),.?":{}|<>]/.test(password)) strength++;

    switch (strength) {
      case 0:
        label = '弱';
        break;
      case 1:
        label = '弱';
        break;
      case 2:
        label = '中';
        break;
      case 3:
        label = '强';
        break;
    }

    return { strength, label };
  },

  // 检查是否可以注册
  checkCanRegister() {
    const canRegister = 
      this.validatePhone(this.data.phone) &&
      this.data.smsCode && this.data.smsCode.length === 6 &&
      this.data.isValidEmail &&
      this.data.emailCode && this.data.emailCode.length === 6 &&
      this.validatePassword(this.data.password) &&
      this.data.password === this.data.confirmPassword &&
      this.data.agreed;

    this.setData({ canRegister });
  },

  // 协议勾选
  onAgreementChange(e) {
    this.setData({
      agreed: e.detail.value.includes('agree')
    });
    this.checkCanRegister();
  },

  // 跳转到登录页面
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 显示用户协议
  showUserAgreement() {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议内容...',
      showCancel: false
    });
  },

  // 显示隐私政策
  showPrivacyPolicy() {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策内容...',
      showCancel: false
    });
  }
});